package cn.takujo.takujoframework.common.util.code_generator;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Setter;

public class DbUtil {

	@Setter
	private static String url;
	@Setter
	private static String user;
	@Setter
	private static String password;

	public List<Map<String, Object>> exeQuerySql(String sql, Object[] parameters) {
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection.prepareStatement(sql);
			for (int i = 0; i < parameters.length; i++) {
				statement.setObject(i + 1, parameters[i]);
			}
			ResultSet executeQuery = statement.executeQuery();
			ResultSetMetaData metaData = executeQuery.getMetaData();
			int columnCount = metaData.getColumnCount();
			List<Map<String, Object>> list = new ArrayList<>();
			while (executeQuery.next()) {
				Map<String, Object> map = new HashMap<>();
				for (int i = 0; i < columnCount; i++) {
					int j = i + 1;
					String columnLabel = metaData.getColumnLabel(j);
					Object object = executeQuery.getObject(j);
					map.put(columnLabel.toLowerCase(), object);
				}
				list.add(map);
			}
			statement.close();
			connection.close();
			return list;
		} catch (SQLException e) {
			throw new ExeQuerySqlFailException(e);
		}
	}

	private Connection getConnection() {
		try {
			return DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			throw new ConnectDatabaseFailException(e);
		}
	}

}
